import { PlusOutlined, SettingOutlined, DeleteOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import { Button, Drawer, message, Modal, Row, Col, Image } from 'antd';
import React, { useState, useRef } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProFormInstance } from '@ant-design/pro-form';
import ProTable from '@ant-design/pro-table';
import type { ActionType } from '@ant-design/pro-table';
import ProDescriptions from '@ant-design/pro-descriptions';
import type { ProDescriptionsItemProps } from '@ant-design/pro-descriptions';
import ProForm, { ModalForm, ProFormSelect, ProFormText, ProFormUploadButton, ProFormDependency } from '@ant-design/pro-form';
import { useAccess } from 'umi';
import { getProviderList, deleteProvider, getProviderInfo, updateProvider, createProvider } from './service'
import { getSupplierList } from '../supplier/service'
import { request } from "@/services/request";
import type { providerTableParams, createProviderParams, picListParams } from './data';

const TableList: React.FC = () => {
  const formRef = useRef<ProFormInstance>();
  const updateFormRef = useRef<ProFormInstance>();

  const imgUpload = {
    maxCount: 1,
    accept: "image/*",

    customRequest: (options) => {
      const { onSuccess, onError, file, } = options;

      var formData = new FormData();
      formData.append('file', file);
      formData.append('token', localStorage.getItem("userToken") || '');

      request('/adminapi/upload', { method: 'POST', data: formData }).then((dataRes) => {
        const _response = { name: file.name, status: "done", path: dataRes.path };
        onSuccess(_response, file);
      }).catch(onError);

    },
    // customRequest: async (e) => {

    //   try {
    //     const dataRes = await uploadImage(e.file);
    //     const filename = e.filename;
    //     message.loading({
    //       key: 'uploading',
    //       content: '图片上传中...',
    //       duration: 0,
    //     })
    //     if (dataRes.code === 200) {

    //       message.destroy('uploading');
    //       message.success('图片上传成功！');

    //       !!formRef ? formRef.current!.setFieldsValue(
    //         filename === 'upload1' ? { product_detail_pic: dataRes.path } :
    //           filename === 'upload2' ? { product_prove_pic: dataRes.path } :
    //             filename === 'upload3' ? { auth_pic: dataRes.path } :
    //               filename === 'upload4' ? { xkz_pic: dataRes.path } :
    //                 filename === 'upload5' ? { zzzch_pic: dataRes.path } : ''
    //       ) : 
    //       updateFormRef.current?.setFieldsValue(
    //         filename === 'upload1' ? { product_detail_pic: dataRes.path } :
    //           filename === 'upload2' ? { product_prove_pic: dataRes.path } :
    //             filename === 'upload3' ? { auth_pic: dataRes.path } :
    //               filename === 'upload4' ? { xkz_pic: dataRes.path } :
    //                 filename === 'upload5' ? { zzzch_pic: dataRes.path } : ''
    //       )
    //     }
    //   } catch (error) {

    //   }
    // },
    // onChange: ({ file }) => {
    //   file.status = 'done';
    // },
  }

  const access = useAccess();

  const [createModalVisible, setCreateModalVisible] = useState(false);
  const [updateModalVisible, setUpdateModalVisible] = useState(false);
  const [showDetail, setShowDetail] = useState(false);
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<providerTableParams>();
  const [picList, setPicList] = useState<picListParams>();

  const providerInfoParams = [
    // {
    //   title: '供应商ID',
    //   dataIndex: 'id',
    // },
    {
      title: '供应商名称',
      dataIndex: 'name',
    },
    {
      title: '状态',
      dataIndex: 'status',
      valueEnum: {
        0: { text: '未启用', status: 'Default', },
        1: { text: '启用中', status: 'Success', },
      },
    },
    {
      title: '货品类型',
      dataIndex: 'products',
    },
    {
      title: '供应商所属',
      dataIndex: 'user_name',
    },
    {
      title: '联系人',
      dataIndex: 'linkman',
      render: (_, rowData) => {
        return `${rowData.linkman} ${rowData.linkphone} `
      }
    },
    {
      title: '统一社会信用代码',
      dataIndex: 'zzzch',
    },
    {
      title: '生产许可明细表',
      dataIndex: 'product_detail_pic',
      render: (_, rowData) => <Image width={100} src={rowData.product_detail_pic} />
    },
    {
      title: '生产许可证明',
      dataIndex: 'product_prove_pic',
      render: (_, rowData) => <Image width={100} src={rowData.product_prove_pic} />
    },
    {
      title: '品牌经销授权书',
      dataIndex: 'auth_pic',
      render: (_, rowData) => <Image width={100} src={rowData.auth_pic} />
    },
    {
      title: '食品经营许可证',
      dataIndex: 'xkz_pic',
      render: (_, rowData) => <Image width={100} src={rowData.xkz_pic} />
    },
    {
      title: '营业执照图片',
      dataIndex: 'zzzch_pic',
      render: (_, rowData) => <Image width={100} src={rowData.zzzch_pic} />
    },
    {
      title: '创建日期',
      dataIndex: 'created_at',
    },
    {
      title: '最后更新日期',
      dataIndex: 'updated_at',
    },
  ]

  return (
    <PageContainer>
      <ProTable<providerTableParams>
        headerTitle="供应商列表"
        loading={false}
        actionRef={actionRef}
        rowKey="id"
        bordered={true}
        columns={[
          {
            title: '供应商名称',
            dataIndex: 'name',
            render: (dom, rowData) => {
              if (access.getProviderInfo) {
                return (
                  <a
                    onClick={() => {
                      setCurrentRow(rowData);
                      setShowDetail(true);
                    }}
                  >
                    {dom}
                  </a>
                );
              } else {
                return (
                  `${dom}`
                );
              }
            },
          },
          {
            title: '状态',
            dataIndex: 'status',
            valueType: 'select',
            filters: true,
            onFilter: true,
            hideInSearch: true,
            valueEnum: {
              0: { text: '未启用', status: 'Default', },
              1: { text: '启用中', status: 'Success', },
            },
          },
          {
            title: '供应商所属',
            dataIndex: 'user_name',
          },
          // {
          //   title: '创建日期',
          //   hideInSearch: true,
          //   dataIndex: 'created_at',
          // },
          {
            title: '操作',
            valueType: 'option',
            render: (dom, rowData) => [
              !!access.updateProvider && rowData.status === 1 && <Button
                key="updateProvider"
                type="primary"
                icon={<SettingOutlined />}
                onClick={() => {
                  setCurrentRow(rowData)
                  setUpdateModalVisible(true)
                }}
              >管理</Button>,
              !!access.deleteProvider && rowData.status === 1 &&
              <Button
                key="deleteProvider"
                type="primary"
                icon={<DeleteOutlined />}
                danger
                onClick={() => {
                  const params = {
                    provider_id: rowData.id
                  }
                  Modal.confirm({
                    title: `是否停用供应商 ${rowData.name} ？`,
                    icon: <ExclamationCircleOutlined />,
                    content: '若确认，此供应商将设置为停用状态。',
                    okText: '确认停用',
                    okType: 'primary',
                    okButtonProps: {
                      danger: true,
                    },
                    cancelText: '取消',
                    onOk: async () => {
                      const res = await deleteProvider({ ...params });

                      if (res.code === 200) {
                        message.success('停用成功！')
                        if (actionRef.current) {
                          actionRef.current.reload();
                        }
                      } else {
                        message.error('停用失败,请重试！')
                      }
                    },
                  });
                }}
              >停用</Button>
            ],
          },
        ]}
        pagination={{
          pageSize: 10,
          current: 1
        }}
        toolBarRender={() => [
          !!access.createProvider &&
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => {
              setCreateModalVisible(true);
            }}
          >新增供应商
          </Button>,
        ]}
        search={{
          resetText: '重置查询',
          searchText: '查询供应商',
        }}
        request={async (params) => {
          const dataParams = {
            page: params.current,
            limit: params.pageSize,
            name: params.name,
            user_name: params.user_name,
          }

          const res = await getProviderList({ ...dataParams });
          return {
            data: res.data.list,
            success: res.code === 200,
            total: res.data.total,
          };
        }}
      />

      {
        !!createModalVisible && (
          <ModalForm<createProviderParams>
            width={800}
            formRef={formRef}
            title='新增供应商'
            visible={createModalVisible}
            onVisibleChange={setCreateModalVisible}
            onFinish={
              async (values) => {

                const params = {
                  ...values,
                  "product_detail_pic": !!values['product_detail_pic'] && !!values['product_detail_pic'][0] ? values['product_detail_pic'][0].response.path : '',
                  "product_prove_pic": !!values['product_prove_pic'] && !!values['product_prove_pic'][0] ? values['product_prove_pic'][0].response.path : '',
                  "xkz_pic": !!values['xkz_pic'] && !!values['xkz_pic'][0] ? values['xkz_pic'][0].response.path : '',
                  "zzzch_pic": !!values['zzzch_pic'] && !!values['zzzch_pic'][0] ? values['zzzch_pic'][0].response.path : '',
                  "auth_pic": !!values['auth_pic'] && !!values['auth_pic'][0] ? values['auth_pic'][0].response.path : '',
                }

                const res = await createProvider({ ...params });

                if (res.code === 200) {
                  message.success('添加成功')
                  !!actionRef.current && actionRef.current.reload();
                } else {
                  message.error('添加失败')
                }
                setCreateModalVisible(false)
              }
            }
          >
            <Row gutter={12}>
              <Col span="8">
                <ProFormText
                  name="name"
                  label="供应商名称"
                  placeholder="请输入供应商名称"
                  rules={[{ required: true, message: '供应商名称不能为空!' }]}
                />
              </Col>
              <Col span="8">
                <ProFormSelect
                  name="oil_depot_id"
                  label="关联仓库"
                  fieldProps={{
                    maxTagCount: 1,
                    virtual: false,
                    mode: 'multiple',
                  }}
                  placeholder="请选择或者搜索关联仓库"
                  rules={[{ required: true, message: '请选择至少一项关联仓库!' }]}
                  request={async (params) => {
                    const res = await getSupplierList({ ...params });
                    const data = res.data.list

                    let optionsData = new Array;

                    data.forEach(item => {
                      optionsData.push({
                        label: item.name,
                        value: item.id,
                      });
                    });

                    return optionsData;
                  }}
                />
              </Col>
              <Col span="8">
                <ProFormText
                  name="products"
                  label="货品类型"
                  placeholder="请输入货品类型"
                />
              </Col>
              <Col span="8">
                <ProFormText
                  name="linkman"
                  label="联系人"
                  placeholder="请输入联系人"
                />
              </Col>
              <Col span="8">
                <ProFormText
                  name="linkphone"
                  label="联系方式"
                  placeholder="请输入联系方式"
                />
              </Col>
              <Col span="8">
                <ProFormText
                  name="zzzch"
                  label="统一社会信用代码"
                  placeholder="请输入统一社会信用代码"
                />
              </Col>
              <Col span="8">
                <ProFormUploadButton
                  label="生产许可明细表"
                  max={1}
                  name="product_detail_pic"
                  fieldProps={{
                    ...imgUpload,
                  }}
                />
              </Col>
              <Col span="8">
                <ProFormUploadButton
                  label="生产许可证明"
                  max={1}
                  name="product_prove_pic"
                  fieldProps={{
                    ...imgUpload,
                  }}
                />
              </Col>
              <Col span="8">
                <ProFormUploadButton
                  label="品牌经销授权书"
                  max={1}
                  name="auth_pic"
                  fieldProps={{
                    ...imgUpload,
                  }}
                />
              </Col>
              <Col span="8">
                <ProFormUploadButton
                  label="食品经营许可证"
                  max={1}
                  name="xkz_pic"
                  fieldProps={{
                    ...imgUpload,
                  }}
                />
              </Col>
              <Col span="8">
                <ProFormUploadButton
                  label="营业执照图片"
                  max={1}
                  name="zzzch_pic"
                  fieldProps={{
                    ...imgUpload,
                  }}
                />
              </Col>
            </Row>
          </ModalForm>
        )
      }

      {
        !!updateModalVisible && (
          <ModalForm
            width={800}
            formRef={updateFormRef}
            title={'管理供应商'}
            visible={updateModalVisible}
            onVisibleChange={setUpdateModalVisible}
            request={async () => {
              const params = {
                provider_id: currentRow?.id,
              }
              const res = await getProviderInfo({ ...params });
              const data = res.data.info;
              data.oil_depot_id = res.data.relations
              data.provider_id = data.id

              // const auth_pic = data.auth_pic,
              //   zzzch_pic = data.zzzch_pic,
              //   xkz_pic = data.xkz_pic,
              //   product_prove_pic = data.product_prove_pic,
              //   product_detail_pic = data.product_detail_pic;

              // setPicList(
              //   {
              //     authPic: auth_pic,
              //     zzzchPic: zzzch_pic,
              //     xkzPic: xkz_pic,
              //     productDetailPic: product_detail_pic,
              //     productProvePic: product_prove_pic,
              //   }
              // )

              return data;
            }}
            onFinish={
              async (value) => {

                // updateFormRef.current?.getFieldsValue(['product_detail_pic'])

                // console.log(updateFormRef.current?.getFieldsValue([]))

                const res = await updateProvider({ ...value });
                if (res.code === 200) {
                  message.success('修改成功')
                  // setPicList({
                  //   authPic: '',
                  //   zzzchPic: '',
                  //   xkzPic: '',
                  //   productDetailPic: '',
                  //   productProvePic: '',
                  // })
                  if (actionRef.current) {
                    actionRef.current.reload();
                  }
                } else {
                  message.error('修改失败')
                }
                setUpdateModalVisible(false)
              }
            }
          >
            <ProFormText
              name="provider_id"
              hidden
            />
            <Row gutter={12}>
              <Col span="8">
                <ProFormText
                  name="name"
                  label="供应商名称"
                  placeholder="请输入供应商名称"
                  rules={[{ required: true, message: '供应商名称不能为空!' }]}
                />
              </Col>
              <Col span="8">
                <ProFormSelect
                  name="oil_depot_id"
                  label="关联仓库"
                  fieldProps={{
                    maxTagCount: 1,
                    virtual: false,
                    mode: 'multiple',
                  }}
                  placeholder="请选择关联仓库"
                  rules={[{ required: true, message: '请选择至少一项关联仓库!' }]}
                  request={async (params) => {
                    const res = await getSupplierList({ ...params });
                    const data = res.data.list
                    const optionsData = new Array;
                    data.forEach(item => {
                      optionsData.push({
                        label: item.name,
                        value: item.id,
                      });
                    });
                    return optionsData;
                  }}
                />
              </Col>
              <Col span="8">
                <ProFormText
                  name="products"
                  label="货品类型"
                  placeholder="请输入货品类型"
                />
              </Col>
              <Col span="8">
                <ProFormText
                  name="linkman"
                  label="联系人"
                  placeholder="请输入联系人"
                />
              </Col>
              <Col span="8">
                <ProFormText
                  name="linkphone"
                  label="联系方式"
                  placeholder="请输入联系方式"
                />
              </Col>
              <Col span="8">
                <ProFormText
                  name="zzzch"
                  label="统一社会信用代码"
                  placeholder="请输入统一社会信用代码"
                />
              </Col>
            </Row>

          </ModalForm>
        )
      }

      {!!showDetail && !!currentRow?.id && (
        <Drawer
          width={600}
          visible={showDetail}
          onClose={() => {
            setCurrentRow(undefined);
            setShowDetail(false);
          }}
          closable={true}
        >
          <ProDescriptions<providerTableParams>
            column={1}
            bordered={true}
            size="small"
            title='供应商详情'
            request={async () => {
              const params = {
                provider_id: currentRow?.id,
              }
              const res = await getProviderInfo({ ...params });
              const data = res.data.info
              data.oil_depot_id = res.data.relations

              return {
                data: data
              };
            }}
            columns={providerInfoParams as ProDescriptionsItemProps<providerTableParams>[]}
          />
        </Drawer>
      )}
    </PageContainer>
  );
};

export default TableList;
